/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file    stm32f1xx_it.c
 * @brief   Interrupt Service Routines.
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2024 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "cJSON.h"
#include "string.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M3 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
 * @brief This function handles Non maskable interrupt.
 */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */
  while (1)
  {
  }
  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
 * @brief This function handles Hard fault interrupt.
 */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
 * @brief This function handles Memory management fault.
 */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
 * @brief This function handles Prefetch fault, memory access fault.
 */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
 * @brief This function handles Undefined instruction or illegal state.
 */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
 * @brief This function handles System service call via SWI instruction.
 */
void SVC_Handler(void)
{
  /* USER CODE BEGIN SVCall_IRQn 0 */

  /* USER CODE END SVCall_IRQn 0 */
  /* USER CODE BEGIN SVCall_IRQn 1 */

  /* USER CODE END SVCall_IRQn 1 */
}

/**
 * @brief This function handles Debug monitor.
 */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
 * @brief This function handles Pendable request for system service.
 */
void PendSV_Handler(void)
{
  /* USER CODE BEGIN PendSV_IRQn 0 */

  /* USER CODE END PendSV_IRQn 0 */
  /* USER CODE BEGIN PendSV_IRQn 1 */

  /* USER CODE END PendSV_IRQn 1 */
}

/**
 * @brief This function handles System tick timer.
 */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f1xx.s).                    */
/******************************************************************************/

/**
 * @brief This function handles DMA1 channel4 global interrupt.
 */
void DMA1_Channel4_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */

  /* USER CODE END DMA1_Channel4_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart1_tx);
  /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */

  /* USER CODE END DMA1_Channel4_IRQn 1 */
}

/**
 * @brief This function handles DMA1 channel5 global interrupt.
 */
void DMA1_Channel5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */

  /* USER CODE END DMA1_Channel5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart1_rx);
  /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */

  /* USER CODE END DMA1_Channel5_IRQn 1 */
}

/**
 * @brief This function handles USART1 global interrupt.
 */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */

  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

/* USER CODE BEGIN 1 */
void ibus2Encoder(long direction, long brake, long speed, signed char toward,
                  char enableRemote, long speedLimit, long brakeLimit, uint8_t *buffer)
{

  /*复位frame报文*/
  uint8_t frame[32];
  memset(frame, 0, 32); // 清空frame缓冲区
  frame[0] = 0x20;      // 写入帧头
  frame[1] = 0x40;      // 写入帧头
  for (int i = 2; i < 30; i += 2)
  {
    frame[i] = 0xDC;
    frame[i + 1] = 0x05;
  }

  /*对齐分辨率*/
  double k_direction = 1000.0 / 65535;
  direction += 32768;
  uint16_t data_direction = (uint16_t)(direction * k_direction + 1000);

  double k_speed = 500.0 / 65535;
  brake = -brake;
  brake += 32767;
  speed = -speed;
  speed += 32767;
  uint16_t data_speed = (uint16_t)((speed - brake) * k_speed + 1500);

  uint16_t data_level = 0;
  switch (toward)
  {
  case 1:
    data_level = 1000;
    break;
  case 0:
    if (data_speed > 1500)
      data_speed = 1500; // 空挡速度始终为1500，但是刹车仍然有效
    break;
  case -1:
    data_level = 2000;
    break;
  }

#if 0
    //打印测试数据
    printf("direction:%d,speed:%d\n",data_direction,data_speed);
#endif

  /*写入数据到frame*/
  frame[2] = data_direction & 0xFF; // 通道1-方向
  frame[3] = (data_direction & 0x0F00) >> 8;
  frame[6] = data_speed & 0xFF; // 通道3-速度
  frame[7] = (data_speed & 0x0F00) >> 8;
  frame[14] = 1000 & 0xFF; // 通道7-远控开关
  frame[15] = (1000 & 0x0F00) >> 8;
  frame[16] = data_level & 0xFF; // 通道8-前进开关
  frame[17] = (data_level & 0x0F00) >> 8;
  frame[18] = 1500 & 0xFF; // 通道9-油门限幅
  frame[19] = (1500 & 0x0F00) >> 8;
  frame[20] = 1500 & 0xFF; // 通道10-刹车限幅
  frame[21] = (1500 & 0x0F00) >> 8;

  /*计算并写入校验位*/
  uint16_t data_check = 0;
  for (int i = 0; i < 30; i++)
  {
    data_check += frame[i];
  }
  data_check ^= 0xFFFF;
  frame[30] = data_check & 0xFF;
  frame[31] = (data_check & 0xFF00) >> 8;

  /*拷贝到目标地址中*/
  memcpy(buffer, frame, 32);

#if 0
    /*打印一帧报文*/
    for(int i = 0;i < 32;i++)
    {
        printf("%02X ",frame[i]);
    }
    printf("\n");
#endif
}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
  if (huart == &huart1)
  {
    // 解析Json
    cJSON *root = cJSON_Parse((const char *)SERIAL1_RX_BUFFER);
    if (root != NULL)
    {
      // 获取并处理各个字段
      cJSON *direction = cJSON_GetObjectItem(root, "direction");
      cJSON *throttle = cJSON_GetObjectItem(root, "throttle");
      cJSON *brake = cJSON_GetObjectItem(root, "brake");
      cJSON *gear = cJSON_GetObjectItem(root, "gear");
      // 编码成ibus2格式
      ibus2Encoder(direction->valueint, brake->valueint, throttle->valueint, gear->valueint, 0, 0, 0, FRAME_SEND_BUFFER);
      // 喂狗
      WATCH_DOOR_DOG_FOOG = 50;
    }
    // 释放 JSON 对象
    cJSON_Delete(root);
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, SERIAL1_RX_BUFFER, sizeof(SERIAL1_RX_BUFFER));
    __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
  }
}
/* USER CODE END 1 */
